<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button
            type="primary"
            @click="addUserShow = true"
          >添加角色</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="rolesList"
        stripe
        style="width: 100%"
        border
      >
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item,index) in scope.row.children"
              :key="item.id"
              :class="['bpborder' , index === 0 ? 'bborder' : '','center']"
            >
              <el-col :span="5">
                <el-tag
                  closable
                  @close="deleteClick(scope.row,item.id)"
                >{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2,index2) in item.children"
                  :key="item2.id"
                  :class="['bborder', index2 === 0 ? 'top-none' : '','center']"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="deleteClick(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      type="warning"
                      @close="deleteClick(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
        ></el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="bjUser(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRolesClick(scope.row)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="isShow(scope.row)"
            >权限分配</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      title="权限分配"
      :visible.sync="rolesisShow"
      width="50%"
      :lock-scroll="false"
      @close="rolesClose"
    >
      <el-tree
        :data="purviewList"
        :props="RolesProps"
        default-expand-all
        show-checkbox
        :default-checked-keys="treeIdList"
        node-key="id"
        ref="treeData"
      ></el-tree>
      <span slot="footer">
        <template>
          <el-button @click="rolesisShow = false">取 消</el-button>
          <el-button
            type="primary"
            @click="setRoles"
          >确 定</el-button>
        </template>
      </span>
    </el-dialog>

    <el-dialog
      title="添加角色"
      :visible.sync="addUserShow"
      width="50%"
      :lock-scroll="false"
    >
      <el-form
        :model="rolesForm"
        :rules="rolesRules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item
          label="角色名称"
          prop="roleName"
        >
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
        >
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <template>
          <el-button @click="addUserShow = false">取 消</el-button>
          <el-button
            type="primary"
            @click="setUserRoles"
          >确 定</el-button>
        </template>
      </span>
    </el-dialog>

    <el-dialog
      title="修改角色"
      :visible.sync="bjShow"
      width="50%"
      :lock-scroll="false"
    >
      <el-form
        :model="changeRoles"
        :rules="rolesRules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item
          label="角色名称"
          prop="roleName"
        >
          <el-input v-model="changeRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
        >
          <el-input v-model="changeRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <template>
          <el-button @click="bjShow = false">取 消</el-button>
          <el-button
            type="primary"
            @click="setChangeRoles"
          >确 定</el-button>
        </template>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getUserData, deleteUser, setData } from "network/homelist";
import {setRoles,changeRoles,setChangeRoles,deleteRoles} from 'network/purview'
export default {
  data() {
    return {
      rolesList: [],
      rolesisShow: false,
      RolesProps: {
        children: "children",
        label: "authName"
      },
      purviewList: [],
      treeIdList: [],
      rolesid: null,
      addUserShow: false,
      rolesForm : {
        roleName : '',
        roleDesc : ''
      },
      rolesRules : {
        roleName : [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      bjShow : false,
      changeRoles : {},
      changeId : null
    }
  },
  methods: {
    getData() {
      return getUserData("/roles").then(res => {
        if (res.data.meta.status === 200) {
          this.rolesList = res.data.data;
          // console.log(this.rolesList)
        } else {
          this.$Message.error("获取失败！");
        }
      });
    },
    async deleteClick(data, id) {
      const isTrue = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (isTrue === "confirm") {
        deleteUser(`roles/${data.id}/rights/${id}`).then(res => {
          if (res.data.meta.status === 200) {
            data.children = res.data.data;
            this.$Message.success(res.data.meta.msg);
          } else {
            this.$Message.error("权限取消失败！");
          }
        });
      } else {
        this.$Message.info("取消删除！");
      }
    },
    async deleteRolesClick(data){
      const isTrue = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (isTrue === "confirm") {
        deleteRoles(`/roles/${data.id}`).then(res => {
          // console.log(res)
          if(res.data.meta.status === 200){
            this.getData()
            this.$Message.success('删除成功！')
          }
          else{
            this.$Message.error('删除失败！')
          }
        })
      } else {
        this.$Message.info("取消删除！");
      }
    },
    isShow(node) {
      getUserData("rights/tree").then(res => {
        if (res.data.meta.status === 200) {
          this.rolesid = node.id;
          // console.log(node)
          this.purviewList = res.data.data;
          this.getListId(node, this.treeIdList);
        } else {
          this.$Message.error("数据获取失败！");
        }
      });
      this.rolesisShow = true;
    },
    getListId(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach(item => {
        this.getListId(item, arr);
      });
    },
    rolesClose() {
      this.treeIdList = [];
    },
    setRoles() {
      const arr = [
        ...this.$refs.treeData.getCheckedKeys(),
        ...this.$refs.treeData.getHalfCheckedKeys()
      ];
      const str = arr.join(",");
      setData(`roles/${this.rolesid}/rights`, { rids: str }).then(res => {
        console.log(res);
        if (res.data.meta.status !== 200) {
          this.$Message.error(res.data.meta.msg);
        }

        this.getData();
        this.rolesisShow = false;
        this.$Message.success(res.data.meta.msg);
      });
    },
    setUserRoles(){
      setRoles('/roles',this.rolesForm).then(res => {
        console.log(res)
        if(res.data.meta.status !== 200){
          this.$Message.error(res.data.meta.msg)
        }
        this.getData()
        this.addUserShow = false
        this.$Message.success(res.data.meta/msg)
      })
    },
    bjUser(data){
      this.bjShow = true
      // console.log(data)
      this.changeId = data.id
      changeRoles(`roles/${data.id}`).then(res => {
        this.changeRoles = res.data.data
        // console.log(this.changeRoles)
      })
    },
    setChangeRoles(){
      setChangeRoles(`roles/${this.changeId}`,{roleName : this.changeRoles.roleName,roleDesc : this.changeRoles.roleDesc}).then(res => {
        // console.log(res)
        if(res.data.meta.status !== 200){
          this.$Message.error("修改失败！")
        }else{
          this.getData()
          this.$Message.success("修改成功！")
          this.bjShow = false
        }

      })
    }
  },
  created() {
    this.getData();
  }
};
</script>
<style lang="less" scoped>
.el-card {
  margin: 20px 0;
}
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.bborder {
  border-top: 1px solid #eee;
}
.bpborder {
  border-bottom: 1px solid #eee;
}
.top-none {
  border-top: none;
}
.center {
  display: flex;
  align-items: center;
}
</style>